package com.wuneng.commonlibrary.hardware.nfc;


import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


import com.wuneng.commonlibrary.R;
import com.wuneng.commonlibrary.eventbus.EventCenter;
import com.wuneng.commonlibrary.eventbus.EventCode;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

public class NFCActivity extends Activity {
    private static final String TAG = "NfcActivity";
    private TextView tvNFCMessage;
    private ImageView nfcIv;
    private PendingIntent mPendingIntent;
    private NfcAdapter mAdapter;
    private Button btnClean;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private int startType = 0;
    public static final int TYPE_MEMBER = 0;
    public static final int TYPE_AREA = 1;
    public static final String EXTRA_START_TYPE = "start_type";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfc);
        getWindow().setLayout(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        tvNFCMessage = (TextView) findViewById(R.id.tag_tv);
        nfcIv = (ImageView) findViewById(R.id.nfc_iv);
        btnClean = (Button) findViewById(R.id.cancel_btn);
        btnClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (Build.VERSION.SDK_INT >= 10)
            mAdapter = NfcAdapter.getDefaultAdapter(this);// get NFC
        if (mAdapter != null && mAdapter.isEnabled()) // if it has Nfc interface
        {
            mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
            // Setup an intent filter for all MIME based dispatches
            IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
            try {
                ndef.addDataType("*/*");
            } catch (IntentFilter.MalformedMimeTypeException e) {
                throw new RuntimeException("fail", e);
            }
            mFilters = new IntentFilter[]{ndef,};
            // Setup a tech list for all NfcF tags
            //mTechLists = new String[][] { new String[] { MifareClassic.class.getName() } };
            mTechLists = new String[][]{new String[]{MifareClassic.class.getName()}, new String[]{NfcF.class.getName()}, new String[]{NfcB.class.getName()}, new String[]{NfcA.class.getName()}, new String[]{NfcV.class.getName()}};
            Intent intent = getIntent();
            Bundle bundle = intent.getExtras();
            startType = bundle.getInt(EXTRA_START_TYPE);
            resolveIntent(intent);
        }
    }

    public static String getUid(Intent intent) {
        byte[] myNFCID = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
        return Converter.getHexString(myNFCID, myNFCID.length);
    }

    void resolveIntent(Intent intent) {
        // 1) Parse the intent and get the action that triggered this intent
        String action = intent.getAction();
        String UID = "";
        // 2) Check if it was triggered by a tag discovered interruption.
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
            // 3) Get an instance of the TAG from the NfcAdapter
            Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            UID = getUid(intent);//可以直接读ID卡号

            //Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_ID);
            // 4) Get an instance of the Mifare classic card from this TAG
            // intent
            MifareClassic mfc = MifareClassic.get(tagFromIntent);
            MifareClassCard mifareClassCard = null;

            try { // 5.1) Connect to card
                mfc.connect();
                boolean auth = false;
                // 5.2) and get the number of sectors this card has..and loop
                // thru these sectors
                int secCount = mfc.getSectorCount();
                mifareClassCard = new MifareClassCard(secCount);
                int bCount = 0;
                int bIndex = 0;
                for (int j = 0; j < secCount; j++) {
                    MifareSector mifareSector = new MifareSector();
                    mifareSector.sectorIndex = j;
                    // 6.1) authenticate the sector
                    auth = mfc.authenticateSectorWithKeyA(j, MifareClassic.KEY_DEFAULT);
                    mifareSector.authorized = auth;
                    if (auth) {
                        // 6.2) In each sector - get the block count
                        bCount = mfc.getBlockCountInSector(j);
                        bCount = Math.min(bCount, MifareSector.BLOCKCOUNT);
                        bIndex = mfc.sectorToBlock(j);
                        for (int i = 0; i < bCount; i++) {

                            // 6.3) Read the block
                            byte[] data = mfc.readBlock(bIndex);
                            MifareBlock mifareBlock = new MifareBlock(data);
                            mifareBlock.blockIndex = bIndex;
                            // 7) Convert the data into a string from Hex
                            // format.
                            bIndex++;
                            mifareSector.blocks[i] = mifareBlock;

                        }
                        mifareClassCard.setSector(mifareSector.sectorIndex, mifareSector);
                    } else { // Authentication failed - Handle it

                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
//				Toast.makeText(NfcActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
            } finally {
                if (mifareClassCard != null) {
                    mifareClassCard.debugPrint();
//                    Intent resultintent = new Intent();
//                    //resultintent.putExtra("result", mifareClassCard.GetCardId());
//                    resultintent.putExtra("result",UID);
//                    setResult(RESULT_OK, resultintent);
//                    NFCActivity.this.finish();
                    EventCenter<String> nfcEvent = new EventCenter<String>(startType == TYPE_MEMBER ? EventCode.CODE_NFC_MEMBER : EventCode.CODE_NFC_AREA, UID);
                    nfcEvent.setNfc(true);

                    EventBus.getDefault().post(nfcEvent);
                    finish();


                }
            }
        }// End of method
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAdapter != null)
            mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
    }

    @Override
    public void onBackPressed() {
        // NfcActivity.this.unregisterReceiver(rbr);
    }

    @Override
    public void onNewIntent(Intent intent) {
        Log.i("Foreground dispatch", "Discovered tag with intent: " + intent);
        resolveIntent(intent);
        // mText.setText("Discovered tag " + ++mCount + " with intent: " +
        // intent);
    }

    @Override
    public void onPause() {
        super.onPause();
//		try{
//		NFCActivity.this.unregisterReceiver(rbr);
//		} catch (Exception e) {
//			// TODO: handle exception
//		}
        if (mAdapter != null)
            mAdapter.disableForegroundDispatch(this);

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        nfcIv.setImageResource(R.drawable.nfc_animlist);
        AnimationDrawable animationDrawable = (AnimationDrawable) nfcIv.getDrawable();
        animationDrawable.start();
    }
}
